package com.awcall.iot.controller;


import com.awcall.iot.common.ResponseResult;
import com.awcall.iot.common.Tree;
import com.awcall.iot.model.Authority;
import com.awcall.iot.service.IAuthorityService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import com.awcall.iot.common.BaseController;

import java.util.List;

/**
 * <p>
 * 权限表 前端控制器
 * </p>
 *
 * @author wuhui
 * @since 2018-03-05
 */
@RestController
@RequestMapping("/admin/authority")
public class AuthorityController extends BaseController {

    @Autowired
    private IAuthorityService authorityService;

    @GetMapping("/index")
    public ResponseResult index(Page<Authority> page, Authority authority) {
        Page<Authority> authorityPage = authorityService.findPage(authority.getTitle(), page);
        return new ResponseResult<>(authorityPage);
    }

    @GetMapping("/show")
    public ResponseResult show(Authority authority) {
        Authority byId = authorityService.selectById(authority.getId());
        return new ResponseResult<>(byId);
    }

    @PostMapping("/create")
    public ResponseResult create(@RequestBody Authority authority) {
        authorityService.insert(authority);
        return new ResponseResult();
    }

    @PostMapping("/update")
    public ResponseResult update(@RequestBody Authority authority) {
        boolean b = authorityService.updateById(authority);
        if (b) {
            return new ResponseResult();
        } else {
            return new ResponseResult<>(1, "修改失败");
        }
    }

    @PostMapping("/delete")
    public ResponseResult delete(@RequestBody Authority authority) {
        authorityService.deleteById(authority);
        return new ResponseResult();
    }

    @GetMapping("/parentAuth")
    public ResponseResult parentAuth() {
        Wrapper<Authority> wrapper = new EntityWrapper<Authority>()
                .isNull(Authority.PARENT_ID);
        List<Authority> authorityList = authorityService.selectList(wrapper);
        return new ResponseResult<>(authorityList);
    }

    @GetMapping("/tree")
    public ResponseResult tree(Integer roleId) {
        List<Tree> treeList;
        if (roleId == null) {
            treeList = authorityService.findAuthorityTree();
        } else {
            treeList = authorityService.findAuthorityTree(roleId);
        }
        return new ResponseResult<>(treeList);
    }

}
